package com.codefish.codefishseckill.controller;

import com.codefish.codefishseckill.exception.GlobalException;
import com.codefish.codefishseckill.vo.RespBean;
import com.codefish.codefishseckill.vo.RespBeanFactory;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 异常处理控制类
 *
 * @author codefish
 * @version 1.0
 * @date 2022/07/05 下午 05:05
 */
@RestControllerAdvice
@Slf4j
public class ExceptionController {


    @ExceptionHandler(Exception.class)
    public RespBean doBindException(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return ex.getExceptionRespBean();
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            String message = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            return RespBeanFactory.fail(message);
        } else if (e instanceof org.springframework.security.access.AccessDeniedException) {
            //处理访问被拒绝异常
            AccessDeniedException ae = (AccessDeniedException) e;
            String message = ae.getMessage();
            return RespBeanFactory.denied(message);
        }
        log.error("系统产生未知异常", e);
        return RespBeanFactory.fail("系统产生内部异常，请联系管理员!");
    }

}
